import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  ACCESS_TOKEN,
  INDEX_MAIN_PAGE_PATH,
  REFRESHTOKEN,
  USER_INFO,
  USER_NAME,
  UI_CACHE_DB_DICT_DATA,
} from '@/store/mutation-types'
import { generateIndexRouter, isOAuth2AppEnv } from '@/utils/util'
import { getAllDict, secondStandardLogin } from './api/api'
import { clearCurrentUrlParams, clearUrlParamsRegex, getUrlParamsAsObject, welcome } from './utils/util'
import warterMark from '@/utils/waterMark.js'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/user/login'] // no redirect whitelist

// to 是即将要去的路径，form是正要离开的路径
router.beforeEach(async (to, from, next) => {
  //
  const urlParams = getUrlParamsAsObject()
  clearCurrentUrlParams()

  if (to.matched && to.matched.length > 2) {
    to.matched.splice(1, to.matched.length - 2)
  }
  NProgress.start() // start progress bar

  // 先判断是不是从其他系统过来的，如果是的话则直接调用登录接口
  if (urlParams.external) {
    const data = {
      ...urlParams,
    }

    try {
      const response = await secondStandardLogin(data)
      if (response.code == 200) {
        const result = response.result
        const userInfo = {
          ...result.userInfo,
          role: result.role,
        }
        Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(REFRESHTOKEN, result.refreshToken, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
        // 再获取一下所有的字典值，将其存起来
        try {
          let dictDataRes = await getAllDict()
          if (dictDataRes.code == 200) {
            Vue.ls.set(UI_CACHE_DB_DICT_DATA, dictDataRes.result)
          }
          commit('SET_TOKEN', result.token)
          commit('SET_REFRESHTOKEN', result.refreshToken)
          commit('SET_INFO', userInfo)
          commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
          commit('SET_AVATAR', userInfo.avatar)
          /*  if (userInfo.role === 'love_and_care') {
            this.$router.push({ path: '/humanisticConcern/oneMap' })
          } else if (userInfo.role === 'key_care') {
            this.$router.push({ path: '/careFamily/largeScreen/index' })
          } else {
            this.$router.push({ path: '/dashboard/analysis' })
          } */
          if (userInfo.role === 'love_and_care') {
            next({ path: '/humanisticConcern/oneMap' })
            return
          } else if (userInfo.role === 'key_care') {
            next({ path: '/careFamily/largeScreen/index' })
            return
          } else {
            next({ path: '/dashboard/analysis' })
            return
          }
        } catch (error) {}
      }
    } catch (error) {}
  }

  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: INDEX_MAIN_PAGE_PATH })
      NProgress.done()
    } else {
      if (store.getters.permissionList.length === 0) {
        store
          .dispatch('GetPermissionList')
          .then((res) => {
            let menuData = res.result.menu
            //console.log(res.message)
            if (menuData === null || menuData === '' || menuData === undefined) {
              return
            }
            let constRoutes = []
            constRoutes = generateIndexRouter(menuData)
            // 添加主界面路由
            store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters)
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // next({ path: '/humanisticConcern/oneMap' })
                const userInfo = Vue.ls.get(USER_INFO)
                if (userInfo.role === 'love_and_care') {
                  next({ path: '/humanisticConcern/oneMap' })
                  return
                } else if (userInfo.role === 'key_care') {
                  next({ path: '/careFamily/largeScreen/index' })

                  return
                } else {
                  //   // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  /* next({ ...to, replace: true }) */

                  next({ path: '/dashboard/analysis' })
                  return

                  // }
                }
              } else {
                // 跳转到目的路由
                next({ path: redirect })
                return
              }
            })
          })
          .catch((err) => {
            console.log(err)
            /* notification.error({
              message: '系统提示',
              description: '请求用户信息失败，请重试！'
            })*/
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
      NProgress.done()
    } else {
      next({ path: '/user/login' })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach((item) => {
  if (item.name !== 'login') {
    // 获取用户名
    let realname = store.state.user.info.realname
    warterMark.set(realname)
  }
  NProgress.done() // finish progress bar
})
